'use strict';

var crypto = require('../utils/crypto');
var http = require('../utils/http');
var logger = require('../utils/log');
var constant = require('../utils/constant');
var roomMgr = require("./roommgr");

var config = null;
var gameServerInfo = null;
var lastTickTime = 0;

var express = require('express');
var app = express();

exports.start = function($config){
    config = $config;

    gameServerInfo = {
        id:config.SERVER_ID,
        gameIP:config.SERVER_IP,
        httpPort:config.SERVER_PORT,
        socketPort:config.SOCKET_PORT,
        account:99999901,
        userId:99999901,
    };

    setInterval(update, 60000);
    update();

    app.listen(config.SERVER_PORT);
    logger.debug("game server is listening", config.SERVER_PORT);
};

app.get('/create_room',function(req, res){
    var userId = req.query.userId;
    var conf = req.query.conf;
    var sign = req.query.sign;

    if(userId == null || sign == null || conf == null){
        logger.error('rpc create_room param error');
        http.send(res, constant.CODE_PARAM_INVALID);
        return;
    }

    var md5 = crypto.md5(userId + config.ROOM_PRI_KEY);
    if(md5 != req.query.sign){
        logger.error('rpc create_room sign error');
        http.send(res, constant.CODE_PARAM_INVALID);
        return;
    }

    var rt = roomMgr.createRoom(userId, conf);
    if (rt == constant.CODE_ERROR) {
        http.send(res, constant.CODE_ROOMNO_ERROR);
    } else {
        http.send(res, constant.CODE_SUCCESS, rt);
    }
    return;
});

app.get('/enter_room',function(req,res){
    var userId = req.query.userId;
    var roomNo = req.query.roomNo;
    var sign = req.query.sign;
    if(userId == null || roomNo == null || sign == null){
        logger.error('rpc enter_room param error');
        http.send(res, constant.CODE_PARAM_INVALID);
        return;
    }

    //验证签名
    var md5 = crypto.md5(roomNo + config.ROOM_PRI_KEY);
    if(md5 != sign){
        logger.error('rpc enter_room sign error');
        http.send(res, constant.CODE_PARAM_INVALID);
        return;
    }

    var code = roomMgr.enterRoom(userId, roomNo);
    if (code != constant.CODE_SUCCESS) {
        http.send(res, code);
    } else {
        var room = roomMgr.getRoomByRoomNo(roomNo);
        var conf = JSON.stringify(room.conf);
        http.send(res, code, {conf:conf, creator:room.creator});
    }
    return;
});

app.get('/ping',function(req,res){
    var sign = req.query.sign;
    var md5 = crypto.md5(config.ROOM_PRI_KEY);
    if(md5 != sign){
        http.send(res, constant.CODE_ERROR, null);
        return;
    }
    http.send(res, constant.CODE_SUCCESS, null);
    return;
});

function update(){
    if(lastTickTime + config.HTTP_TICK_TIME < Date.now()){
        lastTickTime = Date.now();
        gameServerInfo.load = roomMgr.getTotalRooms();
        http.get(config.HTTP_SERVER_SERVER_IP, config.HTTP_SERVER_SERVER_PORT, "/register_server", gameServerInfo, function(code, ret){
            if(code == constant.CODE_SUCCESS){
                logger.debug("game server update", ret.ip);
            } else{
                lastTickTime = 0;
            }
            return;
        });
        // var mem = process.memoryUsage();
        // console.log('Process: heapTotal '+format(mem.heapTotal) + ' heapUsed ' + format(mem.heapUsed) + ' rss ' + format(mem.rss));
    }
};